from app.models import User
from app.extensions import db


class UserService:
    @staticmethod
    def create_user(data):
        try:
            new_user = User(
                id=data.get('id'),
                login_name=data.get('login_name'),
                name=data.get('name'),
                password=data.get('password')
            )
            db.session.add(new_user)
            db.session.commit()
            return {"message": "User created successfully", "status_code": 201, "data": None}
        except Exception as e:
            db.session.rollback()
            return {"error": str(e), "status_code": 400, "data": None}

    @staticmethod
    def get_all_users():
        users = User.query.all()
        user_list = []
        for user in users:
            user_data = {
                'id': user.id,
                'login_name': user.login_name,
                'name': user.name,
                'password': user.password
            }
            user_list.append(user_data)
        return {"status_code": 200, "data": user_list}

    @staticmethod
    def get_user(user_id):
        user = User.query.get(user_id)
        if user:
            user_data = {
                'id': user.id,
                'login_name': user.login_name,
                'name': user.name,
                'password': user.password
            }
            return {"status_code": 200, "data": user_data}
        return {"message": "User not found", "status_code": 404, "data": None}

    @staticmethod
    def update_user(user_id, data):
        user = User.query.get(user_id)
        if user:
            try:
                user.login_name = data.get('login_name', user.login_name)
                user.name = data.get('name', user.name)
                user.password = data.get('password', user.password)
                db.session.commit()
                return {"message": "User updated successfully", "status_code": 200, "data": None}
            except Exception as e:
                db.session.rollback()
                return {"error": str(e), "status_code": 400, "data": None}
        return {"message": "User not found", "status_code": 404, "data": None}

    @staticmethod
    def delete_user(user_id):
        user = User.query.get(user_id)
        if user:
            try:
                db.session.delete(user)
                db.session.commit()
                return {"message": "User deleted successfully", "status_code": 200, "data": None}
            except Exception as e:
                db.session.rollback()
                return {"error": str(e), "status_code": 400, "data": None}
        return {"message": "User not found", "status_code": 404, "data": None}